package com.isoftstone.merchant.controller.mdept;


import com.isoftstone.bank.controller.base.BaseController;
import com.isoftstone.common.Tidings;
import com.isoftstone.merchant.entity.mdept.MDept;
import com.isoftstone.merchant.entity.mdept.MDepttree;
import com.isoftstone.merchant.service.feeUser.FeeUserService;
import com.isoftstone.merchant.service.mdept.IMdeptService;
import com.isoftstone.merchant.service.merchant.MerchantService;
import com.isoftstone.util.*;
import org.apache.commons.lang3.StringUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;



    @Controller
    public class MDeptController extends BaseController {

        @Autowired
        IMdeptService mdeptService;
        @Autowired
        MerchantService merchantService;
        @Autowired
        FeeUserService feeUserService;

        /*
          * 查看部门列表
        */
        @RequiresPermissions("mms-menu.001.001")
        @RequestMapping("/merchant/dept/toDeptTree")
        public ModelAndView getDeprTree(){
            ModelAndView md = new ModelAndView();
            md.setViewName("merchant/sys_management/jigou_manage");
            return md;
        }

        //@RequiresPermissions("mms-menu.001.001")
        @RequestMapping("/merchant/dept/togetDeptTree")
        @ResponseBody
        public Object toDeptTree() {
            Tidings< List<MDepttree>> tidings = new Tidings< List<MDepttree>>();
            String userId=this.getUser().getUserid();
            try {
                String corpId = this.getUser().getCorpId();
                PageData pd = this.getPageData();
                String status = pd.getString("status");
                List<MDept> list = mdeptService.getDeptAll(corpId);    //获取所有部门
                String deptName= merchantService.getCorpNameBycorIp(this.getUser().getCorpId());
                MDept mDept1=new MDept();
                mDept1.setDeptId("0");
                mDept1.setDeptName(deptName);
                mDept1.setSuperDeptId(corpId);
                if (mDept1.getDeptId()!=null){
                    list.add(mDept1);
                }
                List<MDept>deptids=null;
                List<MDept>depts=null;//有几个deptid就有几条线
                deptids=feeUserService.getalldeptByUserId(userId);//得到用户对应的deptid
                depts=new ArrayList<MDept>();//登录用户对应的部门
                if(deptids.size()>0&& com.isoftstone.util.StringUtils.isBlank(status)) {
                    MDept mDept2=new MDept();
                    mDept2.setDeptId("0");
                    mDept2.setDeptName(deptName);
                    mDept2.setSuperDeptId(corpId);
                    if (mDept2.getDeptId()!=null){
                        depts.add(mDept2);
                    }
                    for (MDept mDept : deptids) {
                        List<MDept> mDepts = mdeptService.getUpAlltree(mDept.getDeptId());
                        for(MDept mDept11:mDepts){
                            depts.add(mDept11);
                        }
                    }
                    Set<MDept>set=new HashSet<MDept>(depts);
                    List<MDepttree> mtree = new ArrayList<MDepttree>();
                    if (set!=null && set.size()>0){
                        for (MDept mDept : set) {
                            MDepttree tree = new MDepttree();
                            tree.setId(mDept.getDeptId());
                            tree.setpId(mDept.getSuperDeptId());
                            tree.setName(mDept.getDeptName());
                            tree.setLevel(mDept.getLevel());
                            mtree.add(tree);
                        }
                    }
                    tidings.setT(mtree);
                    tidings.setStatus(Const.SUCCESS);
                }else {
                    List<MDepttree> mtree = new ArrayList<MDepttree>();
                    if (list != null && list.size() > 0) {
                        for (MDept mDept : list) {
                            MDepttree tree = new MDepttree();
                            tree.setId(mDept.getDeptId());
                            tree.setpId(mDept.getSuperDeptId());
                            tree.setName(mDept.getDeptName());
                            tree.setLevel(mDept.getLevel());
                            mtree.add(tree);
                        }
                    }
                    tidings.setT(mtree);
                    tidings.setStatus(Const.SUCCESS);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return tidings;
        }

        /**
         * 新增部门
         * @param
         * @return
         */
       @RequestMapping("/merchant/dept/saveDept")
        @ResponseBody
       //deptId前台传入上级部门id
       //cName前台传入本级部门名称
       //pName前台传入上级部门名称
        public Object saveDept(String deptId,String pName,String cName) {
            Tidings<String> tidings = new Tidings<String>();
            String deptId1 =  UuidUtil.getNumFormatUUID();
            MDept dept=new MDept();
            dept.setDeptId(deptId1);//部门id
            dept.setCorpId(this.getUser().getCorpId());//商户编号
            dept.setSuperDeptId(deptId);//上级部门id
            dept.setDeptName(cName);
            dept.setCreateDate(new Date());
            dept.setCreator(this.getUser().getNickname());
            try {
                if(dept!=null){
                    String deptId2=mdeptService.getdeptIdBydeptId(deptId);
                    if (deptId2!=null){
                        Integer Leavl=mdeptService.getleavlBydeptIdandCorpId(deptId,this.getUser().getCorpId());
                        dept.setLevel(Leavl+1);
                    }else {
                        dept.setLevel(1);
                    }
                };

                if (StringUtils.isBlank(deptId)) {//判断上级id
                    MDept getdept = mdeptService.getRootDept(dept.getCorpId());
                    if (getdept== null) {
                        mdeptService.saveDept(dept);
                        mdeptService.updateDept(dept);//修改名称
                        tidings.setStatus(Const.SUCCESS);
                        tidings.setMsg("保存成功！");
                    } else {
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("请选择上级部门！");
                    }
                } else {
                    String deptname=mdeptService.selectdept(dept.getDeptName(),deptId,this.getUser().getCorpId());//根据deptName与parentid查询部门
                    if(StringUtils.isBlank(deptname)){
                        mdeptService.saveDept(dept);
                        tidings.setStatus(Const.SUCCESS);
                        tidings.setMsg("保存成功！");
                    }else {
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("同一个部门下，部门名称不能重复！");
                    }
                }
            } catch (Exception e) {
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("保存失败！");
                e.printStackTrace();
            }
            return tidings;
        }


        /**
         * 更新部门
         * @param
         * @return
         *
         */
        @RequestMapping("/merchant/dept/UpdateDept")
        @ResponseBody
        public Object updateDept( String deptId,String name) {
            Tidings<String> tidings = new Tidings<String>();

            try {
                MDept dept=mdeptService.getDeptById(deptId);
                if (dept == null) {
                    tidings.setStatus(Const.ERROR);
                    tidings.setMsg("根机构不可以编辑!");
                    return tidings;
                }
                dept.setUpdateDate(new Date());
                dept.setDeptName(name);
                dept.setUpdator(this.getUser().getNickname());


                /**
                 * 登录用户和修改的部门不在一个企业，不能修改
                 */
                if (!StringUtils.equals(this.getUser().getCorpId(),dept.getCorpId())  ) {
                    tidings.setStatus(Const.ERROR);
                    tidings.setMsg("不是同一个部门，不能修改!");
                    return tidings;
                }
                /**
                 * 查询上级部门ID
                 *
                 */
                MDept Dept = mdeptService.getDeptById(deptId);
                if(Dept==null ){
                    tidings.setStatus(Const.ERROR);
                    tidings.setMsg("根机构不可以编辑！");
                    return tidings ;
                }else{
                  String SuperDeptId=Dept.getSuperDeptId();//父级id
                  List<MDept> list=mdeptService.getDeptBySupId(SuperDeptId);//查询所有父级id为SuperDeptId 的部门
                    for (MDept mDept : list) {
                        if (StringUtils.equals(name,mDept.getDeptName())){
                            tidings.setStatus(Const.ERROR);
                            tidings.setMsg("同一部门下，部门名称不能重复！");
                            return tidings;
                        }
                    }
                }
                mdeptService.updateDept(dept);
                tidings.setStatus(Const.SUCCESS);
                tidings.setMsg("修改成功！");
            } catch (Exception e) {
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("修改失败！");
                e.printStackTrace();
            }
            return tidings;
        }
    /*
    * 删除部门
    * */
        @RequestMapping("/merchant/dept/deleteDept")
        @ResponseBody
        public Object deleteDept(String deptId) {
            Tidings<String> tidings = new Tidings<String>();
            ModelAndView md = new ModelAndView();
            try {
                //当前登陆者机构id
                String corpId=this.getUser().getCorpId();//从session中获取corpId
                MDept dept = mdeptService.getDeptById(deptId);
                String corpId1=dept.getCorpId(); //得到该机构商户编号
                if(StringUtils.equals(corpId,corpId1)) {
                          String count=mdeptService.getUserDeptById(deptId);
                           List <MDept> deptList=mdeptService.getParentDeptByIdandCorpId(deptId,corpId1);//根据上级部门id与改部门商户id查找下级部门
                    if(deptList.size()==0){//判断该机构下是否无下级机构
                           if(StringUtils.equals(count,"0")) {//判断该机构下是否无绑定商户人员
                               mdeptService.deleteDept(deptId);
                               tidings.setStatus(Const.SUCCESS);
                               tidings.setMsg("删除成功！");
                           }else {
                               tidings.setStatus(Const.ERROR);
                               tidings.setMsg("删除失败,该机构下存在用户！");
                           }
                    }else {
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("需要删除该机构下的子机构,才可以删除该机构！");
                    }
                }else {
                    md.setViewName("404");
                    return md;
                }
            } catch (Exception e) {
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("删除失败！");
                e.printStackTrace();
            }
            return tidings;
        }


        /**
         * 到修改和添加页面
         * @param deptId
         * @return
         */


        @RequestMapping("/merchant/dept/toDeptEdit")
        public ModelAndView toDeptEdit(String deptId) {
            System.out.print(deptId);
            ModelAndView md = new ModelAndView();
            try {
                String mId="1";//需要从session获得登录用户的corpIde
                MDept dept = mdeptService.getDeptById(deptId);
                //得到该部门企业编号
                if(dept!= null && StringUtils.equals(mId,dept.getCorpId())) {
                    List<MDept> list = mdeptService.getDeptAll(mId);    //获取所有部门
                    String json = JsonUtil.beanToJson(list);
                    json = json.replaceAll("deptId", "id").replaceAll("superDeptId", "pId").replaceAll("deptName", "name");
                    md.addObject("zTreeNodes", json);
                    md.addObject("dept", dept);
                }else if(StringUtils.isBlank(deptId)){
                    List<MDept> list = mdeptService.getDeptAll(mId);    //获取所有部门
                    String json = JsonUtil.beanToJson(list);
                    json = json.replaceAll("deptId", "id").replaceAll("superDeptId", "pId").replaceAll("deptName", "name");
                    md.addObject("zTreeNodes", json);
                    md.addObject("dept", dept);
                }else {
                    md.setViewName("404");
                    return md;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            md.setViewName("merchant/dept/dept_edit");
            return md;
        }
            /*
            *
            * 下载机构模板
            * */
        @RequestMapping(value = "merchant/dept/download")
        public ModelAndView download(){
            ModelAndView md=new ModelAndView();
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
                titles.add("上级机构名称");        //1
                titles.add("本机构名称");        //2
                dataMap.put("titles", titles);
                List<PageData> subList = new ArrayList<PageData>();
                PageData subpd = new PageData();
                subpd.put("var1","中国银行");
                subpd.put("var2", "小一班");
                PageData subpd1 = new PageData();
                subpd1.put("var1","中国银行");
                subpd1.put("var2", "小二班");
                PageData subpd2 = new PageData();
                subpd2.put("var1","小一班");
                subpd2.put("var2", "小小一班");
                PageData subpd3 = new PageData();
                subpd3.put("var1","小二班");
                subpd3.put("var2", "小小二班");
                subList.add(subpd);
                subList.add(subpd1);
                subList.add(subpd2);
                subList.add(subpd3);
                dataMap.put("varList",subList);
                dataMap.put("name", "Mdept");
                dataMap.put("sheetName", "机构");
                ObjectExcelView erv = new ObjectExcelView();
                md = new ModelAndView(erv, dataMap);
            return md;
        }


        public final String[] FFiles = new String[]{".xls",".xlsx"};
        /*
        *
        * 导入机构报表
        * */
        @RequestMapping(value = "merchant/dept/upload",method =RequestMethod.POST,produces = {"text/html;charset=UTF-8"})
       // @ResponseBody
        public void upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
                Tidings<List<MDept>> tidings = new Tidings<>();
            String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                List<String> deptNamelist = new ArrayList<String>();
                Set<String> deptNameSet=new HashSet<String>();
            List<Tidings>list1=new ArrayList<Tidings>();
           this.getResponse().setContentType("text/html;charset=UTF-8");
                int i = 0;
                try {
                    String corpName=merchantService.getCorpNameBycorIp(this.getUser().getCorpId());
                    if (Arrays.asList(FFiles).contains(extName)) {
                        String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;                                //文件上传路径
                        String fileName = FileUpload.fileUp(file, filePath, "cominfoexcelUp");
                        List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName, 2, 0);        //执行读EXCEL操作,读出的数据导入List 2:从第2行开始；0:从第A列开始；0:第0个sheet
                        if (listPd.size() == 0) {
                            tidings.setStatus(Const.ERROR);
                            tidings.setMsg("导入文件不能为空");
                        }
                        //*存入数据库操作======================================*//
                        List<MDept> resultList = new ArrayList<MDept>();
                        int j=0;
                        for (i = 0; i < listPd.size(); i++) {
                            MDept mDept = new MDept();
                            if ((listPd.get(i).getString("col0") == null || listPd.get(i).getString("col0") == "") &&
                                    (listPd.get(i).getString("col1") == null || listPd.get(i).getString("col1") == "")) {
                                         j++;
                                    if (j == listPd.size()) {
                                        tidings.setStatus(Const.ERROR);
                                        tidings.setMsg("导入的文件内容不能为空!");
                                    }
                             } else {
                                String superdeptName = listPd.get(i).getString("col0");//上级机构名称 i从0开始
                                String deptName = listPd.get(i).getString("col1");//本机机构名称
                                deptNamelist.add(deptName);
                                deptNameSet.add(deptName);
                                if(deptNamelist.size()==deptNameSet.size()){
                                    if(StringUtils.isNotBlank(superdeptName)){
                                        if(StringUtils.equals(corpName,superdeptName)){//如果导入上级机构名称等于机构默认名称
                                            mDept.setSuperDeptId("0");
                                            mDept.setDeptId(UuidUtil.getNumFormatUUID());
                                            mDept.setCorpId(this.getUser().getCorpId());
                                            mDept.setDeptName(deptName);
                                            mDept.setLevel(1);
                                            mDept.setOrderNo(1);
                                            mDept.setCreateDate(new Date());
                                            mDept.setCreator(this.getUser().getNickname());

                                        }else{
                                            if(StringUtils.equals(corpName,deptName)){
                                                tidings.setStatus(Const.ERROR);
                                                tidings.setMsg("导入的第" + (i + 1) + "行数据出错,本机机构名称不能为系统默认生成机构名称!");
                                                throw new RuntimeException("导入的第" + (i + 1) + "行数据出错,本机机构名称不能为系统默认生成机构名称!");
                                            }
                                            if(resultList.size()!=0){
                                                for (MDept dept : resultList) {
                                                    String Name=dept.getDeptName();
                                                    Integer Level=dept.getLevel();
                                                    if(StringUtils.equals(superdeptName,Name)){
                                                        mDept.setSuperDeptId(dept.getDeptId());
                                                        mDept.setDeptId(UuidUtil.getNumFormatUUID());
                                                        mDept.setCorpId(this.getUser().getCorpId());
                                                        mDept.setDeptName(deptName);
                                                        mDept.setLevel(Level+1);
                                                        mDept.setOrderNo(1);
                                                        mDept.setCreateDate(new Date());
                                                        mDept.setCreator(this.getUser().getNickname());
                                                        break;
                                                    }
                                                    if(StringUtils.isBlank(dept.getDeptId())){
                                                        tidings.setStatus(Const.ERROR);
                                                        tidings.setMsg("导入的第" + (i) + "行数据出错,上级机构名称是否正确!");
                                                        throw new RuntimeException("导入的第" + (i) + "行数据出错,上级机构名称是否正确!");
                                                    }
                                                }
                                            }else {
                                                tidings.setStatus(Const.ERROR);
                                                tidings.setMsg("请在第一级上级机构填系统默认生成机构名称!");
                                                throw new RuntimeException("请在第一级上级机构填系统默认生成机构名称！");
                                            }
                                        }
                                    }
                                }else {
                                    tidings.setStatus(Const.ERROR);
                                    tidings.setMsg("导入的第" + (i + 1) + "行数据出错,本机机构名称不能重复!");
                                    throw new RuntimeException("导入的第" + (i + 1) + "行数据出错,本机机构名称不能重复!");
                                }
                                    resultList.add(mDept);
                            }
                        }
                        if (!Const.ERROR.equals(tidings.getStatus())) {
                          mdeptService.saveExcelData(resultList);
                            tidings.setStatus(Const.SUCCESS);
                            tidings.setMsg("共成功上传"+resultList.size()+"行！");
                        }
                    } else {
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("上传文件格式不正确，请选择xls格式文件上传!");
                        throw new RuntimeException("上传文件格式不正确，请选择xls格式文件上传");
                    }
                } catch (Exception e) {
                    tidings.setStatus(Const.ERROR);
                    e.printStackTrace();
                    logger.error("导入第" + (i + 1) + "行数据出错，请检查", e);
                }
            list1.add(tidings);
            try {
                 this.getResponse().getWriter().write(JsonUtil.beanToJson(list1));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}
